package com.bjpowernode.security06jwtredismysql.service.impl;


import com.bjpowernode.security06jwtredismysql.domain.SysUser;
import com.bjpowernode.security06jwtredismysql.mapper.SysUserMapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义用户服务
 * 用来认证的
 * security来调用该方法,不是我们自己调用的
 */
@Component
public class AppUserServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 1.根据用户查询数据库的用户对象
     * 2.查询用户的权限
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser sysUser = sysUserMapper.findByUsername(username);

        if (sysUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        //查询用户对应的权限
        List<String> authorities = sysUserMapper.findPermissionsByUserId(sysUser.getUserId());

        /*
            将permissions set到SysUser中的权限属性中
            SysUser 属性的类型：List<GrantedAuthority>
            我们查出的类型： List<String>
            所以需要将List<String> permissions转换成List<GrantedAuthority>
         */
        List<SimpleGrantedAuthority> permissions = new ArrayList<>();
        for (String a : authorities) {
            permissions.add(new SimpleGrantedAuthority(a));
        }

        sysUser.setPermissions(permissions);

        return sysUser;
    }
}
